package p2p.simulation;

import java.util.ArrayList;
import java.util.List;

import p2p.logic.connection.client.Client;
import p2p.peer.Peer;

public class PeerManager {
	
	private static PeerManager instance; 
	
	private List<Peer> peerList;
		
	private GraphUpdater updater;
	
	private PeerManager(){
		peerList = new ArrayList<Peer>();
	}

	public static PeerManager getInstance(){
		
		if (instance == null )
			instance = new PeerManager();
		
		return instance;
	
	}
	
	public void addGraphUpdater(GraphUpdater updater){
		this.updater = updater;
	}
	
	public  void addPeerAndSimulate(Peer peer){
	
		this.peerList.add(peer);
		
		if (Simulation.getInstance().isRunning()){
			
			Simulator simulator = new Simulator(peer);
		
			simulator.simulate();
		}
	
	}
	
	
	
	
	public List<Peer> getPeerList() {
		return peerList;
	}

	public void listPeers(){
		for (Peer p : peerList){
			System.out.print(p.getId() + ":");
			for (Client c : p.getNeighbors()){
				System.out.print(c.getPort() + " , ");
			}
			System.out.println();
		}
	}

	public void leaveClient(Object obj) {
		if (obj instanceof String){
			Peer peer = null;
			
			for (Peer p : peerList){
				if (p.getPeerAsClient().getPort() == Integer.parseInt((String) obj)){
					peer = p;
					break;
				}
			}
			
			if (peer != null){
				peer.leave();
				peerList.remove(peer);
			}
		
		}
	
	}
	
	public void updateGraph(Peer peer){
		this.updater.update();
	}
	
	
}
